package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.StationResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.dto.UserProfileResponse;
import com.ugoodtech.mdcc.web.service.ExportReportService;
import com.ugoodtech.mdcc.web.service.StationService;
import com.ugoodtech.mdcc.web.service.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, Inc.
 */


@Api(description = "维修站接口")
@Controller
@RequestMapping("/station")
public class StationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StationController.class);
    @Autowired
    UserRepository systemUserRepository;
    @Autowired
    UserService systemUserService;

    @Autowired
    StationService stationService;

    @Autowired
    StationRepository stationRepository;

    @Autowired
    DepartmentRepository departmentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ExportReportService exportReportService;


    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

//    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
//    public JsonResponse getUsers(
//            @RequestParam(value = "searchParam") String searchParam, Pageable pageable) throws Exception {
//        isUserLogin();
//        Page<User> systemUsers = systemUserService.queryUser(searchParam, Constants.ROLE_ADMIN, pageable);
//        return JsonResponse.successResponseWithPageData(systemUsers);
//    }

    @ApiOperation("删除未补充完整的维修站")
    @RequestMapping(value = "deleteUnCheckOutStation", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteUnCheckOutStation(@RequestParam("stationIdList") String stationIdList) {
        String[] deleteId = stationIdList.split(",");
        for (String id : deleteId) {
            Station station = stationRepository.findOne(Long.valueOf(id));
            if (null != station && !station.isCheckStation()) {
                station.setDeleted(true);
                station.setEnabled(false);
                String stationNum = station.getStationNum();
                station.setStationNum(stationNum + "_deleted");
                String stationName = station.getName();
                station.setName(stationName + "_deleted");
                stationRepository.save(station);
            } else {
                continue;
            }
        }
        return JsonResponse.successResponse();
    }

    @ApiOperation("按条件查询维修站")
    @RequestMapping(value = "findOneStation", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse findOneStation(@ApiParam("当前登陆用户ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                       @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                                       @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                       @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                       @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                       @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前用户");
        }
        return stationService.checkStation(user, province, city, category, brand, stationName);
    }

    @ApiOperation("维修站列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = StationResponse.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllDepartment(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                         @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                         @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                         @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                         @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                         @ApiParam("关键字") @RequestParam(value = "stationName", required = false) String stationName,
                                         @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) Long customerStat,
                                         @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) Long customerType,
                                         @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String patintBrand,
                                         @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                         @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                         @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                         @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId,
                                         Pageable pageable) {
        isUserLogin();
        JsonResponse station = stationService.queryStation(customerStat, customerType, patintBrand, productPosition, province, city, category, brand, stationName, stationNum, pageable, loginUserId, userName, departmentId);
        return station;
    }

    @ApiOperation("客户资料导出")
    @RequestMapping(value = "/exportToExcel", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse exportToExcel(HttpServletRequest request,
                                      @ApiParam("登陆用户ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                      @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                      @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                      @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                      @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                      @ApiParam("关键字") @RequestParam(value = "stationName", required = false) String stationName,
                                      @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) Long customerStat,
                                      @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) Long customerType,
                                      @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String patintBrand,
                                      @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                      @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                      @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                      @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId) {
        isUserLogin();
        JsonResponse jsonResponse = stationService.exportToExcel(customerStat, customerType, patintBrand, productPosition, province, city, category, brand, stationName, stationNum, loginUserId, userName, departmentId);
        List<List<String>> stationInfoLists = (List<List<String>>) jsonResponse.getData();
        String templetPath = request.getSession().getServletContext().getRealPath("");
        String fileName = "客户资料导出.xlsx";
        String sheetName = "客户资料";
        XSSFWorkbook wb = getStationInfoExport(null, sheetName, stationInfoLists);
        try {
            FileOutputStream outputStream = new FileOutputStream(new File(templetPath + "/export/" + fileName));
            wb.write(outputStream);
            outputStream.close();
            String filePath = Constants.v_starServiceUrl + "/export/" + fileName;
//            String filePath = "http://vr.duluxdesigner.com.cn/export/" + fileName;
//            String filePath = "http://116.62.64.140:51002/export/" + fileName;

            try {
                Map<String, Object> searchParams = new HashMap<>();
                searchParams.put("省份", province);
                searchParams.put("城市", city);
                searchParams.put("维修站类型", category);
                searchParams.put("品牌", brand);
                searchParams.put("维修站名称", stationName);
                if (null != customerStat) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(customerStat);
                    searchParams.put("客户状态", questionAnswerOption.getName());
                }
                if (null != customerType) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(customerType);
                    searchParams.put("客户类型", questionAnswerOption.getName());
                }
                if (null != patintBrand) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.parseLong(patintBrand));
                    searchParams.put("油漆品牌", questionAnswerOption.getName());
                }
                if (null != productPosition) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.parseLong(productPosition));
                    searchParams.put("品牌定位", questionAnswerOption.getName());
                }
                searchParams.put("维修站编号", stationNum);
                searchParams.put("外勤人员姓名", userName);
                String desc = "筛选了:";
                for (String key : searchParams.keySet()) {
                    if (null != searchParams.get(key) && !StringUtils.isEmpty(searchParams.get(key).toString())) {
                        desc += (key + "=>" + searchParams.get(key) + " ,");
                    }
                }
                if ("筛选了:".equals(desc)) {
                    desc = "";
                }
                Map<String, Object> data = new HashMap<>();
                data.put("str", desc);
                userLogService.addUserLog(this.getCurrentUser(), null,
                        LogConstants.operate_type_send_export,
                        LogConstants.business_type_customer, null, data);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return JsonResponse.successResponseWithData(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResponse.successResponse();
    }

    private static String[] stationTitleArray = {"创建人", "创建时间", "最近一次修改人", "最近一次修改时间", "维修站ID", "站点名称", "省份", "城市", "地址", "客户状态", "客户类型", "联系人姓名", "联系人职位", "联系人手机", "维修站类型", "具体品牌",
            "其他品牌备注", "维修站所属集团", "该维修站每月钣喷维修钣件数", "每月钣喷维修台次", "该维修站油漆月用量", "油漆品牌", "选择其他油漆品牌的请说明", "品牌定位", "油漆服务商", "前处理人数", "面漆人数", "抛光人数",
            "调漆人数", "喷漆房数量（个）", "气压", "光亮度", "光亮度备注", "洁净度", "洁净度备注", "可否进行加温", "加温类型", "加温类型备注", "空压机类型", "是否安装冷干机", "压缩空气洁净度", "喷漆房内有没有油水分离器",
            "打磨设备类型", "圆形打磨机数量", "长方形打磨机数量", "打磨机质量", "打磨机吸尘能力", "该维修站红外线烤灯状况，配备台数", "HVLP喷枪（把）", "传统喷枪（把）", "中涂喷枪（把）", "喷枪喷涂质量", "底漆品牌",
            "底漆型号", "原子灰品牌", "原子灰型号", "中涂底漆品牌", "中涂底漆型号", "底色漆品牌", "底色漆型号", "清漆品牌", "清漆型号", "中涂底漆前是否使用水磨", "颜色准确度", "颜色准确度备注", "最常用的颜色查询工具",
            "颜色查询工具备注", "AkzoNobel服务商人员来店服务时使用的颜色工具（多选）", "颜色工具备注", "返工率最高的颜色（必须填写色号）", "配方非常稳定的颜色（必须填写色号）", "问题类型", "问题类型备注", "问题类型具体说明",
            "诉求类型", "诉求类型备注", "诉求类型具体说明"};


    private XSSFWorkbook getStationInfoExport(XSSFWorkbook workbook, String sheetName, List<List<String>> stationInfoLists) {
        if (workbook == null) {
            workbook = new XSSFWorkbook();
        }
        XSSFSheet sheet = workbook.createSheet(sheetName);
        for (int i = 0; i < stationInfoLists.get(0).size(); i++) {
            sheet.setColumnWidth(i, 15 * 2 * 256);
        }
        XSSFFont titleFont = workbook.createFont();
        titleFont.setFontName("微软雅黑");
        titleFont.setFontHeightInPoints((short) 10);
        titleFont.setColor(IndexedColors.WHITE.getIndex());
        titleFont.setBold(true);
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        XSSFColor titleColor = new XSSFColor(new java.awt.Color(68, 114, 196));
        titleStyle.setFillForegroundColor(titleColor);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setLeftBorderColor(titleColor);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setRightBorderColor(titleColor);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setTopBorderColor(titleColor);

        XSSFColor myColor1 = new XSSFColor(new java.awt.Color(180, 198, 231));
        XSSFCellStyle titleStyle2 = workbook.createCellStyle();
        titleStyle2.setAlignment(HorizontalAlignment.CENTER);
        titleStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle2.setFillForegroundColor(myColor1);
        titleStyle2.setBorderTop(BorderStyle.THIN);
        titleStyle2.setBorderBottom(BorderStyle.THIN);
        titleStyle2.setBorderRight(BorderStyle.THIN);
        titleStyle2.setTopBorderColor(myColor1);
        XSSFFont font2 = workbook.createFont();
        font2.setFontName("微软雅黑");
        font2.setFontHeightInPoints((short) 10);
        titleStyle2.setFont(font2);


        XSSFCellStyle titleStyle3 = workbook.createCellStyle();
        titleStyle3.setAlignment(HorizontalAlignment.CENTER);
        titleStyle3.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle3.setFillForegroundColor(myColor1);
        titleStyle3.setBorderTop(BorderStyle.THIN);
        titleStyle3.setBorderBottom(BorderStyle.THIN);
        titleStyle3.setBorderRight(BorderStyle.NONE);
        titleStyle3.setTopBorderColor(myColor1);
        titleStyle3.setFont(font2);

        XSSFColor myColor2 = new XSSFColor(new java.awt.Color(217, 225, 242));
        XSSFCellStyle titleStyle4 = workbook.createCellStyle();
        titleStyle4.setAlignment(HorizontalAlignment.CENTER);
        titleStyle4.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle4.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle4.setFillForegroundColor(myColor2);
        titleStyle4.setBorderTop(BorderStyle.THIN);
        titleStyle4.setBorderBottom(BorderStyle.THIN);
        titleStyle4.setBorderRight(BorderStyle.NONE);
        titleStyle4.setTopBorderColor(myColor2);
        titleStyle4.setFont(font2);

        XSSFCellStyle titleStyle5 = workbook.createCellStyle();
        titleStyle5.setAlignment(HorizontalAlignment.CENTER);
        titleStyle5.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle5.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle5.setFillForegroundColor(myColor2);
        titleStyle5.setBorderTop(BorderStyle.THIN);
        titleStyle5.setBorderBottom(BorderStyle.THIN);
        titleStyle5.setBorderRight(BorderStyle.THIN);
        titleStyle5.setTopBorderColor(myColor2);
        titleStyle2.setFont(font2);

        XSSFRow row1 = sheet.createRow(0);
        XSSFCell cell1 = null;
        //创建标题
        for (int i = 0; i < stationTitleArray.length; i++) {
            cell1 = row1.createCell(i);
            cell1.setCellValue(stationTitleArray[i]);
            cell1.setCellStyle(titleStyle);
        }
        XSSFCell sheet1Cell2 = null;
        for (int i = 0; i < stationInfoLists.size(); i++) {
            row1 = sheet.createRow(i + 1);
            for (int j = 0; j < stationInfoLists.get(i).size(); j++) {
                sheet1Cell2 = row1.createCell(j);
                //将内容按顺序赋给对应的列对象
                if (j == stationInfoLists.get(i).size() - 1) {
                    if (i % 2 == 0) {
                        sheet1Cell2.setCellStyle(titleStyle2);
                    } else {
                        sheet1Cell2.setCellStyle(titleStyle5);
                    }

                    try {
                        sheet1Cell2.setCellValue(Long.valueOf(stationInfoLists.get(i).get(j)));
                    } catch (Exception e) {
                        sheet1Cell2.setCellValue(stationInfoLists.get(i).get(j));
                    }

                } else {
                    if (i % 2 == 0) {
                        sheet1Cell2.setCellStyle(titleStyle3);
                    } else {
                        sheet1Cell2.setCellStyle(titleStyle4);
                    }
                    try {
                        sheet1Cell2.setCellValue(Long.valueOf(stationInfoLists.get(i).get(j)));
                    } catch (Exception e) {
                        //品牌
                        if (j == 12) {
                            if (StringUtils.isNotEmpty(stationInfoLists.get(i).get(j))) {
                                String[] brandArray = stationInfoLists.get(i).get(j).split(",");
                                int index = 1;
                                StringBuffer stringBuffer = new StringBuffer("");
                                for (String brandStr : brandArray) {
                                    stringBuffer.append(brandStr + ",");
                                    if (index == 5) {
                                        stringBuffer.append("\n");
                                        index = 1;
                                    }
                                    index++;
                                }
                                sheet1Cell2.setCellValue(stringBuffer.toString());
                            }
                        } else {
                            sheet1Cell2.setCellValue(stationInfoLists.get(i).get(j));
                        }
                    }
                }
            }
        }
        return workbook;
    }

    @ApiOperation("维修站下拉列表")
    @RequestMapping(value = "/comboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse stationComboList(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                         @ApiParam("关键字") @RequestParam(value = "stationName", required = false) String stationName) {
        if (StringUtils.isEmpty(stationName)) {
            return JsonResponse.successResponseWithData(new Object[0]);
        }
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前用户");
        }
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
//        builder.and(qStation.checkStation.eq(true));
//        builder.and(qStation.user.isNotNull());
//        builder.and(qStation.province.isNotNull());
//        builder.and(qStation.city.isNotNull());
//        builder.and(qStation.contact.isNotNull());
        builder.and(qStation.name.like("%" + stationName + "%"));
        List<Station> stations = (List<Station>) stationRepository.findAll(builder);
        List<LabelValue> labelValues = new ArrayList<>();
        if (stations != null) {
            for (Station station : stations) {
                LabelValue labelValue = new LabelValue(station.getName(), station.getId() + "");
                labelValues.add(labelValue);
            }
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    @ApiOperation("导出维修站列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = StationResponse.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/exprotStation", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse exprotStation(HttpServletRequest request,
                                      @ApiParam("登陆用户ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                      @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                      @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                      @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                      @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                      @ApiParam("关键字") @RequestParam(value = "stationName", required = false) String stationName,
                                      @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) Long customerStat,
                                      @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) Long customerType,
                                      @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String patintBrand,
                                      @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                      @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                      @ApiParam("外勤人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                      @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId,
                                      Pageable pageable) throws Exception {
        List<StationResponse> stationResponses = (List<StationResponse>) getAllDepartment(loginUserId, province, city, category, brand, stationName, customerStat, customerType, patintBrand, productPosition, stationNum, userName, departmentId, pageable).getData();
        String templetPath = request.getSession().getServletContext().getRealPath("");
        String filePath = exportReportService.getStationInfo(stationResponses, templetPath);
        filePath = Constants.v_starServiceUrl + ":51001" + filePath;
//        filePath = "http://vr.duluxdesigner.com.cn:51001" + filePath;
        return JsonResponse.successResponseWithData(filePath);
    }


    @ApiOperation("删除维修站")
    @RequestMapping(value = "/deleteStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse deleteStation(@ApiParam(value = "用户数据库id", required = true) @RequestParam(value = "stationId") Long stationId) {
        isUserLogin();
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
        }
        if (station.isDeleted() == true) {
            return JsonResponse.errorResponseWithError("抱歉", "该维修站已经被删除");
        }
        station.setDeleted(true);
        stationRepository.save(station);
        userLogService.addUserLog(this.getCurrentUser(), station.getStationNum(),
                LogConstants.operate_type_delete,
                LogConstants.business_type_station, null, null);

        return JsonResponse.successResponse();
    }

    @ApiOperation("冻结维修站")
    @RequestMapping(value = "/freezeActivationStation", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse freezeActivationStation(@ApiParam(value = "用户数据库id") @RequestParam(value = "stationId") Long stationId) {
        isUserLogin();
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
        }
        if (station.isDeleted() == true) {
            return JsonResponse.errorResponseWithError("抱歉", "该维修站已经被删除");
        }
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.user.stationId.eq(stationId));
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        String operation = LogConstants.operate_type_freeze;
        if (station.isEnabled() == false) {
            station.setEnabled(true);
            freezeUser(userProfileList, true);
            operation = LogConstants.operate_type_enable;
        } else {
            station.setEnabled(false);
            freezeUser(userProfileList, false);
            operation = LogConstants.operate_type_freeze;
        }
        stationRepository.save(station);
        userLogService.addUserLog(this.getCurrentUser(), station.getStationNum(),
                operation,
                LogConstants.business_type_station, null, null);
        return JsonResponse.successResponse();
    }

    /**
     * 根据维修站冻结下属用户
     *
     * @param userProfileList
     * @param enabled
     */
    private void freezeUser(List<UserProfile> userProfileList, boolean enabled) {
        for (UserProfile userProfile : userProfileList) {
            userProfile.setEnabled(enabled);
            userProfileRepository.save(userProfile);
            User user = userProfile.getUser();
            if (user == null) {
                continue;
            }
            user.setEnabled(enabled);
            userRepository.save(user);
        }
    }

    @ApiOperation("获取维修站下属用户")
    @RequestMapping(value = "/getStationUserList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getStationUserList(@ApiParam(value = "用户数据库id") @RequestParam(value = "stationId") Long stationId,
                                           Pageable pageable) {
//        isUserLogin();
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
        }
        if (station.isDeleted() == true) {
            return JsonResponse.errorResponseWithError("抱歉", "该维修站已经被删除");
        }
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.stationList.any().id.eq(stationId));
        Page<UserProfile> userProfileList = userProfileRepository.findAll(builder, pageable);
        List<UserProfileResponse> userProfileResponseList = new ArrayList<>();
        for (UserProfile user : userProfileList.getContent()) {
            UserProfileResponse response = new UserProfileResponse(user);
            userProfileResponseList.add(response);
        }
        Page<UserProfileResponse> page = new PageImpl(userProfileResponseList, pageable, userProfileList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    @ApiOperation("添加维修站下属用户")
    @RequestMapping(value = "/addStationUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse addStationUser(@ApiParam(value = "维修站Id") @RequestParam(value = "stationId") Long stationId,
                                       @ApiParam(value = "姓名") @RequestParam(value = "userName") String userName,
                                       @ApiParam(value = "职位") @RequestParam(value = "position") String position,
                                       @ApiParam(value = "联系电话") @RequestParam(value = "mobilePhone") String mobilePhone,
                                       @ApiParam(value = "执行此操作的管理员ID") @RequestParam(value = "loginUserId", required = false) Long userId) {
//        isUserLogin();
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
        }
        if (station.isDeleted() == true) {
            return JsonResponse.errorResponseWithError("抱歉", "该维修站已经被删除");
        }
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(position) || StringUtils.isEmpty(mobilePhone)) {
            return JsonResponse.errorResponseWithError("抱歉", "填写的内容不能为空");
        }
//        UserProfile managerUser = userProfileRepository.findByUserId(userId);
//        if (managerUser == null) {
//            return JsonResponse.errorResponseWithError("抱歉", "未找到当前管理员");
//        }
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.realName.eq(userName));
        builder.and(qUserProfile.mobilePhone.eq(mobilePhone));
        builder.and(qUserProfile.position.eq(position));
        UserProfile userProfile = userProfileRepository.findOne(builder);
        User user = userRepository.findByUsername(mobilePhone);
        if (userProfile == null && user == null) {
            user = new User();
            user.setUsername(mobilePhone);
            user.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
            user.setUserType(UserType.customer);
            user.setStationId(stationId);
            user = userRepository.save(user);

            userProfile = new UserProfile();
            userProfile.setUser(user);
            userProfile.setTelephone(mobilePhone);
            userProfile.setRealName(userName);
            userProfile.setPosition(position);
            List<Station> stationList = new ArrayList<>();
            stationList.add(station);
            userProfile.setStationList(stationList);
//            userProfile.setAddUser(managerUser);
            userProfileRepository.save(userProfile);
            Map<String, Object> data = new HashMap<>();
            String desc = "姓名:" + userProfile.getRealName();
            data.put("str", desc);
            userLogService.addUserLog(this.getCurrentUser(), station.getStationNum(),
                    LogConstants.operate_type_add,
                    LogConstants.business_type_people, null, data);
            return JsonResponse.successResponse();
        } else {
            return JsonResponse.errorResponseWithError("抱歉", "您填写的用户信息已经存在");
        }
    }

    @ApiOperation("删除维修站下属用户")
    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse deleteUser(Long loginUserId,
                                   Long userId) {
        UserProfile userProfile = userProfileRepository.findOne(userId);
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        UserProfile manageUserProfile = userProfileRepository.findByUserId(loginUserId);
        if (manageUserProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到管理员用户");
        }
        userProfile.setAddUser(manageUserProfile);
        userProfile.setEnabled(false);
        userProfile.setDeleted(true);
        userProfileRepository.save(userProfile);
        User user = userProfile.getUser();
        user.setEnabled(false);
        user.setDeleted(true);
        userRepository.save(user);
        Map<String, Object> data = new HashMap<>();
        data.put("str", userProfile.getRealName());
        userLogService.addUserLog(this.getCurrentUser(), null,
                LogConstants.operate_type_delete,
                LogConstants.business_type_people, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("编辑维修站下属用户")
    @RequestMapping(value = "/editStationUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse editStationUser(Long loginUserId,
                                        @ApiParam(value = "用户ID") @RequestParam(value = "userId") Long userId,
                                        @ApiParam(value = "维修站ID") @RequestParam(value = "stationId") Long stationId,
                                        @ApiParam(value = "用户名称") @RequestParam(value = "userName") String userName,
                                        @ApiParam(value = "职务") @RequestParam(value = "position", required = false) String position,
                                        @ApiParam(value = "电话") @RequestParam(value = "telephone") String telephone) {
        UserProfile userProfile = userProfileRepository.findOne(userId);
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        UserProfile manageUserProfile = userProfileRepository.findByUserId(loginUserId);
        if (manageUserProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到管理员用户");
        }
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此维修站");
        }
        User telephoneUser = userRepository.findByUserName_phone(telephone);
        if (telephoneUser != null && !telephoneUser.getId().equals(userProfile.getUser().getId())) {
            return JsonResponse.errorResponseWithError("抱歉", "此手机号已经被使用");
        }
        String desc = "";
        if (!userName.equals(userProfile.getRealName())) {
            desc += "姓名 :";
            desc += userProfile.getRealName() + "-->>" + userName + ",";
        }
        if (!position.equals(userProfile.getPosition())) {
            desc += "职务 :";
            desc += userProfile.getPosition() + "-->>" + position + ",";
        }
        User user = userProfile.getUser();
        if (!telephone.equals(userProfile.getTelephone())) {
            desc += "联系电话 :";
            desc += user.getUsername() + "-->>" + telephone + ",";
        }
        userProfile.setAddUser(manageUserProfile);
        userProfile.setRealName(userName);
        userProfile.setPosition(position);
        userProfile.setTelephone(telephone);
        userProfileRepository.save(userProfile);

        user.setUsername(telephone);
        user.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
        userRepository.save(user);

        Map<String, Object> data = new HashMap<>();
        data.put("str", desc);
        userLogService.addUserLog(this.getCurrentUser(), station.getStationNum(),
                LogConstants.operate_type_edit,
                LogConstants.business_type_people, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("维修站下拉框")
    @RequestMapping(value = "/stationComboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse stationComboList(@ApiParam(value = "维修站关键字") @RequestParam(value = "name", required = false) String name) {
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qStation.name.eq(name));
        }
        List<Station> stationList = (List<Station>) stationRepository.findAll(builder);
        List<LabelValue> comboData = new ArrayList<>();
        for (Station station : stationList) {
            LabelValue labelValue = new LabelValue(station.getName(), station.getId() + "");
            comboData.add(labelValue);
        }
        return JsonResponse.successResponseWithData(comboData);
    }


}
